import Singleton from "./Singleton";
import MsgHints from "../framwork/MsgHints";

import Utils from '../utils/Utils';
const tt = window["tt"];

const { ccclass, property } = cc._decorator;
export default class AdCenter extends Singleton {
    VideoAd = null;

    constructor() {
        super();

        if (tt&& tt.createRewardedVideoAd) {
            this.VideoAd = tt.createRewardedVideoAd({
                adUnitId: '5fcc2a5bf3bbtw8fhi'
            });

            this.VideoAd.onError((res) => {
                console.log("onError", res);
                MsgHints.show("广告加载错误");
            });

            this.VideoAd.onLoad(() => {
                // console.log('广告加载成功');
            })

            this.VideoAd.onClose(res => {
                if (res && res.isEnded || res === undefined) {
                    cc.log("正常播放结束，可以下发游戏奖励")
                    this.callBack(true);
                }
                else {
                    cc.log("播放中途退出，不下发游戏奖励")
                    this.callBack(false);
                }
            })

            if (tt.createInterstitialAd) {
                this.interstitialAd = tt.createInterstitialAd({
                    adUnitId: '2gaeew7ku3w3l7lwu6'
                })
            }
        }
    }

    interstitialAd = null
    public showinterstitialAd() {
        // 在适合的场景显示插屏广告
        if (this.interstitialAd) {
            this.interstitialAd.show().catch((err) => {
                console.log(err);
            })
        }
    }

    public showGridAd() 
    {
       return
    }

    public hideGridAd() {
        return
    }


    private callBack: Function;
    private _lasttryplaytime: number = 0;
    public play(type: number, callback: Function) {
        if (Utils.getServerTime() - this._lasttryplaytime < 1000) {
            console.log("点击过于频繁")
            return;
        }
        console.log("尝试播放广告")
        this._lasttryplaytime = Utils.getServerTime();
        this.callBack = callback;

        if ( this.VideoAd) {
            this.VideoAd.show().catch(() => {
                this.VideoAd.load()
                    .then(() => this.VideoAd.show())
                    .catch(err => {
                        cc.log('激励视频 广告显示失败');
                        this.callBack(false);
                    })
            })
        }
        else {
            this.callBack(true);
        }
    }
}